package com.efrei.uchat.message;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import com.efrei.uchat.exception.UChatException;
import com.efrei.uchat.io.Session;

public class CroomUsersMessage extends Message {

	private String croom;
	private Map<String, Integer> users = new HashMap<String, Integer>();
	
	public CroomUsersMessage(String text) throws UChatException {
		super(text);
		// get croom
		croom = fields.get(0);
		// and users
		int size = fields.size();
		for (int i = 1; i < size-1; i+=2) {
			users.put(fields.get(i),
					Integer.valueOf(fields.get(i+1)));
		}
	}
	
	public CroomUsersMessage(int sessionId, String croom) {
		super(Headers.CROOM_USERS_MESSAGE, sessionId);
		this.croom = croom;
	}
	
	/**
	 * add croom to list
	 * @param topic
	 * @param restricted if croom requires password
	 * @return
	 */
	public CroomUsersMessage addSession(Session session) {
		users.put(session.getChatter().getPseudo(),
				session.getId());
		return this;
	}
	
	private void updateFields() {
		fields.clear();
		fields.add(croom);
		for (Entry<String, Integer> elt : users.entrySet()) {
			fields.add(elt.getKey());
			fields.add(elt.getValue().toString());
		}
	}
	
	@Override
	public String toString() {
		updateFields();
		return super.toString();
	}
	
	public String getCroom() {
		return croom;
	}

	public Map<String, Integer> getUsers() {
		return users;
	}
}
